import win32api         #需要安装pywin32模块
import win32gui
import win32con
import win32process
import time
import os
import sys
from pywinauto.application import Application   #需要安装pywinauto模块
from pywinauto.mouse import click, move, keyboard
from docx import Document                       #需要安装python-docx模块
from openpyxl import Workbook                   #需要安装openpyxl模块
from typing import List, Tuple

def get_hwnd():  
    try:
        hwnd = win32gui.FindWindow("Chrome_WidgetWin_1", "电投壹")  # 根据类名或窗口名找到主窗口句柄
        return hwnd
    except Exception as e:
        print(e)

def get_process(hwnd):
    try:
        thr, proc = win32process.GetWindowThreadProcessId(hwnd)  # 获取当前窗口进程id
        print(proc)
        #将窗口显示设为正常大小，然后设置窗口大小为1920*1040
        # win32gui.ShowWindow(hwnd, win32con.SW_NORMAL)
        # win32gui.MoveWindow(hwnd, 0, 0, 1920, 1040, 1)
        return proc
    except Exception as e:
        print(e)

def set_top(hwnd):
    try:
        # win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)  # 若窗口最小化或被遮挡则显示
        win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
        win32gui.SetForegroundWindow(hwnd)  # 将窗口设为顶层
    except Exception as e:
        print(e)

def get_app(proc):
    try:
        # title对应inspect中name, control_type对应inspect中LocalizedControlType的英文
        app = Application(backend='uia').connect(process=proc)  # 根据进程号连接到应用
        time.sleep(1)
        return app  # 返回应用对象
    except Exception as e:
        print(e)

def get_desktop(app):
    # info = app.top_window().child_window(title="消息", control_type="Hyperlink")
    # info.click_input()

    desktop = app.top_window().child_window(title="工作台", control_type="Hyperlink")
    desktop.click_input()
    time.sleep(1)

    desktop_text = app.top_window().child_window(title="工作台", control_type="Text", found_index=1)
    desktop_text.click_input()
    time.sleep(1)

    return desktop

def get_deep_seek(app):
    deep_seek = app.top_window().child_window(title="DeepSeek内网体验版", control_type="Text", found_index=0)
    deep_seek.click_input()
    # deep_seek.print_control_identifiers()
    # deep_seek.print_ctrl_ids()
    time.sleep(1)
    return deep_seek

def get_inputbox(app, hwnd, send_coord1, send_coord2):
    input_box = app.top_window().child_window(title="有问题，尽管问...按Shift+Enter换行", control_type="Edit")
    time.sleep(3)
    input_box.type_keys("你是谁？")
    # 点击提交给模型按钮
    set_top(hwnd)
    move(send_coord1)
    click(button='left', coords=send_coord1)

    # 3秒后，点击暂停模型输出按钮
    time.sleep(3)
    set_top(hwnd)
    move(send_coord2)
    click(button='left', coords=send_coord2)

    return input_box

def commit_question(app, hwnd, input_box, zan_coord, cai_coord, commit_fankui_coord,send_coord1, send_coord2):
    i = 0
    while i <= 9:
        #输入问题并提交请求
        input_box.type_keys("你是谁？")
        time.sleep(1)

        # 第一次提交按钮位置和第二次提交按钮位置不同，所以需要判断
        if i > 0:
            # 点击提交给模型按钮
            set_top(hwnd)
            move(send_coord2)
            click(button='left', coords=send_coord2)

            # 3秒后，点击暂停模型输出按钮
            time.sleep(3)
            set_top(hwnd)
            move(send_coord2)
            click(button='left', coords=send_coord2)
        else:
            # 点击提交给模型按钮
            set_top(hwnd)
            move(send_coord1)
            click(button='left', coords=send_coord1)

            # 3秒后，点击暂停模型输出按钮
            time.sleep(3)
            set_top(hwnd)
            move(send_coord2)
            click(button='left', coords=send_coord2)

        if i >= 5:  # 第5次输入问题后，再点赞点踩反馈
            time.sleep(1)
            #点赞答案
            #zan_coord = (589, 725)
            set_top(hwnd)
            move(zan_coord)
            click(button='left', coords=zan_coord)

            #点踩答案
            time.sleep(1)
            #cai_coord = (620, 725)
            set_top(hwnd)
            move(cai_coord)
            click(button='left', coords=cai_coord)
            time.sleep(1)

            #输入并提交反馈内容
            fankui_box = app.top_window().child_window(title="请输入反馈内容", control_type="Edit")
            fankui_box.type_keys("无")
            #commit_fankui_coord = (1098, 666)
            set_top(hwnd)
            move(commit_fankui_coord)
            click(button='left', coords=commit_fankui_coord)

        i += 1
    print("输入并提交问题完成！点赞点踩反馈完成！")

def upload_file(hwnd, app, input_box, file, upload_file_coord, send_coord2):
    # for o in input_box.parent().children():
    #     properties = o.legacy_properties()
    #     # print(properties)
    #     auto_id = o.automation_id()
    #     o.draw_outline('red')

    i = 0
    time.sleep(3)
    while i <= 4:

        #打开上传选择文件对话框
        # 上传文件的控件索引有时是-4，有时是-3，不知道是什么原因
        # 如果再出错可以改为模拟鼠标操作，upload_coord = (1735,985)
        # input_box.parent().children()[-4].click_input()
        #input_box.parent().children()[-3].click_input()
        #time.sleep(3)
        set_top(hwnd)
        move(upload_file_coord)
        click(button='left', coords=upload_file_coord)
        time.sleep(1)

        #选择文件对话框
        fd = app.top_window().child_window(title="打开", control_type="Window", class_name="#32770")
        # fd.print_control_identifiers()
        try:
            file_name = app.top_window().child_window(title="文件名(N):", control_type="Edit", auto_id="1148")
            fd.child_window(title="文件名(N):", control_type="Edit", auto_id="1148").set_edit_text(file)
            # file_name.type_keys(file)
            file_name.click_input()
        except:
            file_name = app.top_window().child_window(title="文件名(N):", control_type="Edit", auto_id="1148")
            # file_name.type_keys(file)
            file_name.click_input()

        try:
            open_btn = fd.child_window(title="打开(O)", control_type="SplitButton", auto_id="1")
            open_btn.click_input()
        except:
            open_btn = fd.child_window(title="打开(O)", control_type="Button", auto_id="1")
            open_btn.click_input()

        ibox = app.top_window().child_window(title="请输入对于上传文件的需求，Shift+Enter可换行", control_type="Edit")
        time.sleep(2)

        try:
            ibox.type_keys(" 请总结上传文件内容")
        except:
            input_box.type_keys(" 请总结上传文件的内容")

        # 点击提交给模型按钮
        set_top(hwnd)
        move(send_coord2)
        click(button='left', coords=send_coord2)

        # 3秒后，点击暂停模型输出按钮
        time.sleep(3)
        set_top(hwnd)
        move(send_coord2)
        click(button='left', coords=send_coord2)
        i += 1

    print("上传文件完成！")

def document_check(name, hwnd, app, upload_file_coord, file, send_coord2):
    i = 0
    time.sleep(3)
    while i <= 9:
        # 打开上传选择文件对话框
        # app.top_window().child_window(title="文档校对", control_type="Button").click_input()
        bt_name = app.top_window().child_window(title=name, control_type="Button")
        bt_name.click_input()

        #app.top_window().child_window(title="从本地选择文件", control_type="Text").click_input()
        # 点击上传文件按钮
        set_top(hwnd)
        move(upload_file_coord)
        click(button='left', coords=upload_file_coord)
        time.sleep(1)

        fd = app.top_window().child_window(title="打开", control_type="Window", class_name="#32770")
        try:
            file_name = app.top_window().child_window(title="文件名(N):", control_type="Edit", auto_id="1148")
            fd.child_window(title="文件名(N):", control_type="Edit", auto_id="1148").set_edit_text(file)
            # file_name.type_keys(file)
            file_name.click_input()
        except:
            file_name = app.top_window().child_window(title="文件名(N):", control_type="Edit", auto_id="1148")
            file_name.type_keys(file)
            file_name.click_input()

        try:
            open_btn = fd.child_window(title="打开(O)", control_type="SplitButton", auto_id="1")
            open_btn.click_input()
        except:
            open_btn = fd.child_window(title="打开(O)", control_type="Button", auto_id="1")
            open_btn.click_input()

        time.sleep(1)
        # 点击提交给模型按钮
        set_top(hwnd)
        move(send_coord2)
        click(button='left', coords=send_coord2)

        # 3秒后，点击暂停模型输出按钮
        time.sleep(3)
        set_top(hwnd)
        move(send_coord2)
        click(button='left', coords=send_coord2)
        time.sleep(1)

        bt_name.click_input()
        i += 1
    print(name +"完成！")

def excel_help(app, hwnd, input_box, upload_file_coord, file, send_coord2):

    bt_excel = app.top_window().child_window(title="excel助手", control_type="Button")
    ibox = app.top_window().child_window(title="请上传表格或将文件直接拖拽至框内，描述需求，累积文件大小不要超过10M，最多上传8个文件", control_type="Edit")

    i = 0
    while i <= 9:
        bt_excel.click_input()
        try:
            ibox.type_keys("请统计班级平均分数。")
        except:
            input_box.type_keys("请统计班级平均分数。")

        set_top(hwnd)
        move(upload_file_coord)
        click(button='left', coords=upload_file_coord)
        time.sleep(1)

        # 选择文件对话框
        fd = app.top_window().child_window(title="打开", control_type="Window", class_name="#32770")
        try:
            file_name = app.top_window().child_window(title="文件名(N):", control_type="Edit", auto_id="1148")
            fd.child_window(title="文件名(N):", control_type="Edit", auto_id="1148").set_edit_text(file)
            file_name.click_input()
        except:
            file_name = app.top_window().child_window(title="文件名(N):", control_type="Edit", auto_id="1148")
            file_name.type_keys(file)
            file_name.click_input()

        try:
            open_btn = fd.child_window(title="打开(O)", control_type="SplitButton", auto_id="1")
            open_btn.click_input()
        except:
            open_btn = fd.child_window(title="打开(O)", control_type="Button", auto_id="1")
            open_btn.click_input()

        # 点击提交给模型按钮
        set_top(hwnd)
        move(send_coord2)
        click(button='left', coords=send_coord2)

        # 3秒后，点击暂停模型输出按钮
        time.sleep(3)
        set_top(hwnd)
        move(send_coord2)
        click(button='left', coords=send_coord2)

        bt_excel.click_input()
        i += 1
    print("excel助手完成！")

def doc_convert(app, hwnd, upload_file_coord, file, send_coord2):

    file_trans = app.top_window().child_window(title="文档转换", control_type="Button")

    i = 0
    while i <= 9:
        file_trans.click_input()

        # 点击上传文件按钮
        set_top(hwnd)
        move(upload_file_coord)
        click(button='left', coords=upload_file_coord)
        time.sleep(1)

        # 选择文件对话框
        fd = app.top_window().child_window(title="打开", control_type="Window", class_name="#32770")
        try:
            file_name = app.top_window().child_window(title="文件名(N):", control_type="Edit", auto_id="1148")
            fd.child_window(title="文件名(N):", control_type="Edit", auto_id="1148").set_edit_text(file)
            file_name.click_input()
        except:
            file_name = app.top_window().child_window(title="文件名(N):", control_type="Edit", auto_id="1148")
            file_name.type_keys(file)
            file_name.click_input()

        try:
            open_btn = fd.child_window(title="打开(O)", control_type="SplitButton", auto_id="1")
            open_btn.click_input()
        except:
            open_btn = fd.child_window(title="打开(O)", control_type="Button", auto_id="1")
            open_btn.click_input()

        # 点击提交给模型按钮
        set_top(hwnd)
        move(send_coord2)
        click(button='left', coords=send_coord2)

        # 3秒后，点击暂停模型输出按钮
        time.sleep(3)
        set_top(hwnd)
        move(send_coord2)
        click(button='left', coords=send_coord2)

        file_trans.click_input()

        i += 1
    print("文档转换完成！")

def tips_help(app, hwnd, tips_help_coord, send_coord2):
    i = 0
    time.sleep(3)
    while i <= 9:
        # 点击"提示词帮助"按钮
        app.top_window().child_window(title="提示词帮助", control_type="Button").click_input()

        # 选择第一个提示词帮助-公告，以下坐标为提示词帮助-公告的坐标
        set_top(hwnd)
        move(tips_help_coord)
        click(button='left', coords=tips_help_coord)

        # 点击提交给模型按钮
        set_top(hwnd)
        move(send_coord2)
        click(button='left', coords=send_coord2)
        time.sleep(3)

        # 点击暂停模型输出按钮
        set_top(hwnd)
        move(send_coord2)
        click(button='left', coords=send_coord2)
        time.sleep(1)
        i += 1
    print("提示词帮助完成！")

def suggestion(app):
    i = 0
    time.sleep(3)
    while i <= 2:
        sg = app.top_window().child_window(title="意见反馈", control_type="Button")
        time.sleep(1)
        sg.click_input()

        app.top_window().child_window(title="请您详细描述您的反馈内容", control_type="Edit").type_keys("无")
        time.sleep(1)

        commit= app.top_window().child_window(title="提交反馈", control_type="Button")
        time.sleep(1)
        commit.click_input()
        i += 1
    print("意见反馈完成！")

def create_docx_file(file):
    """
    如果文件不存在，则创建docx文件
    Returns:
       无
    """
    if not os.path.exists(file):
        doc = Document()
        doc.add_heading('文档校对', 0)
        doc.add_paragraph('能源行业正面临数字化转型升级的关键期，作为国家电投集团数字化技术专业平台公司，需要通过系统化产品管理提升数字化技术应用能力。解决产品研发分散、技术标准不统一等问题，为了应对这些挑战，公司亟需建立一套规范、高效的产品管理体系。')
        doc.add_paragraph('‌规范产品管理体系‌：确保产品管理工作的有序进行，需要建立一套系统的管理体系，明确各相关部门的职责和工作流程。')
        doc.add_paragraph('‌提升产品研发实施能力‌：通过制定管理办法，可以进一步优化产品研发流程，提升研发效率和质量，从而增强公司的产品研发实施能力。')
        doc.save(file)

def create_excel_file(file):
    """
    如果文件不存在，则创建excel文件
    :param file: 文件名称
    :return: 无
    """
    if not os.path.exists(file):
        workbook = Workbook()
        worksheet = workbook.active
        worksheet.title = "MySheet"
        worksheet.append(["姓名", "学号", "性别", "班级", "科目", "分数"])
        worksheet.append(["小王", "2019001", "男", "软件工程", "语文", "80"])
        worksheet.append(["小张", "2019002", "女", "软件工程", "语文", "90"])
        worksheet.append(["小李", "2019003", "男", "软件工程", "语文", "70"])

        workbook.save(file)
def get_all_resolutions() -> List[Tuple[int, int]]:
    """
    获取当前显示设备所有适用的分辨率
    Returns:
        List[Tuple[int, int]]: 所有适用的分辨率列表，每个分辨率为一个 (宽度, 高度) 元组
    """
    i = 0
    resolutions = []
    while True:
        try:
            devmode = win32api.EnumDisplaySettings(None, i)
            resolution = (devmode.PelsWidth, devmode.PelsHeight)
            if resolution not in resolutions:
                resolutions.append(resolution)
            i += 1
        except Exception as e:
            break
    return resolutions

def get_all_resolutions() -> None:
    """
    打印当前显示设备所有适用的分辨率
    """
    resolutions = get_all_resolutions()
    for resolution in resolutions:
        print(resolution)

def get_current_resolution() -> Tuple[int, int]:
    """
    获取并打印当前屏幕分辨率
    Returns:
        Tuple[int, int]: 当前屏幕分辨率 (宽度, 高度)
    """
    try:
        devmode = win32api.EnumDisplaySettings(None, win32con.ENUM_CURRENT_SETTINGS)
        current_resolution = (devmode.PelsWidth, devmode.PelsHeight)
        print(f"当前分辨率: {current_resolution[0]}x{current_resolution[1]}")
        return current_resolution
    except Exception as e:
        print(f"获取当前分辨率时出错: {e}")
        return (0, 0)

def set_screen_resolution(width: int, height: int) -> None:
    """
    设置屏幕分辨率
    Args:
        width (int): 目标宽度
        height (int): 目标高度
    """
    try:
        devmode = win32api.EnumDisplaySettings(None, win32con.ENUM_CURRENT_SETTINGS)
        devmode.PelsWidth = width
        devmode.PelsHeight = height
        result = win32api.ChangeDisplaySettings(devmode, win32con.CDS_UPDATEREGISTRY)
        if result == win32con.DISP_CHANGE_SUCCESSFUL:
            print(f"分辨率已更改为: {width}x{height}")
        else:
            print("更改分辨率失败")
    except Exception as e:
        print(f"更改分辨率时出错: {e}")

def check_screen_resolution():
    """
    检测屏幕分辨率，如果屏幕分辨率大于1920*1080，则设置屏幕分辨率为1920*1080；
    如果屏幕分辨率小于1920*1080，则提示不支持，需用inspect程序检测deep_seek发送按钮坐标，并手动调整
    :return:
    """
    current_resolution = get_current_resolution()
    if current_resolution[0] > 1920 and current_resolution[1] > 1080:
        return 1
    elif current_resolution[0] < 1920 and current_resolution[1] < 1080:
        print("当前分辨率小于1920*1080，请手动调整")
        return -1
    else:
        print("当前分辨率等于1920*1080，请勿调整")
        return 0

if __name__ == '__main__':

    # old_resolution = get_current_resolution()
    # res = check_screen_resolution()
    # if res == 1:
    #     set_screen_resolution(1920, 1080)
    #     print("已设置屏幕分辨率为1920*1080")
    # elif res == -1:
    #     print("请手动调整屏幕分辨率")
    #     exit()

    #根据不同的屏幕分辨率，获取屏幕按钮坐标(默认分辨率是1920*1080)
    send_coord1 = (1839, 756)       # deepseek最初点击发送按钮的坐标
    send_coord2 = (1839, 978)       # deepseek点击发送按钮后，新的发送按钮坐标(最初的发送按钮坐标位置和第二次及以后的发送按钮坐标位置不同)
    tips_help_coord = (1865, 185)   # 提示词帮助-“公告-使用”按钮的坐标

    zan_coord = (550, 720)          # 第6次输入问题后，点赞按钮的坐标
    cai_coord = (578, 720)          # 第6次输入问题后，踩按钮的坐标
    commit_fankui_coord = (1090, 665)   # 点踩-提交反馈按钮的坐标
    upload_file_coord  = (400, 980)    # 上传文件按钮的坐标

    arguments = sys.argv[:]         # 从命令行参数中获取文件路径
    # 提取第一个元素（也是唯一一个元素）
    full_path = arguments[0]
    # 分离路径和文件名
    file_path = os.path.dirname(full_path)  # D:\temp\ddy_deepseek
    file_name = os.path.basename(full_path)  # auto_diantouyi.py

    #创建word文件
    docx_file = "文档说明.docx"
    create_docx_file(docx_file)
    #docx_path_file_name = os.getcwd() + "\\" + docx_file
    docx_path_file_name = file_path + "\\" + docx_file
    fn_name = ("文档校对", "文档总结", "中英互译")
    # file1 = r'd:\temp\attachment\upload_file.doc'
    print("正在处理文件：", docx_path_file_name)

    #创建excel文件
    excel_file = "文档说明.xlsx"
    create_excel_file(excel_file)
    excel_path_file_name = file_path + "\\" + excel_file

    hwnd = get_hwnd()
    proc = get_process(hwnd)

    # 设置窗口置顶
    set_top(hwnd)

    # 获取app
    app = get_app(proc)

    # 获取工作台页面
    desktop = get_desktop(app)
    # 获取deep_seek页面
    deep_seek = get_deep_seek(app)
    # 获取deepseek输入框
    input_box = get_inputbox(app, hwnd, send_coord1, send_coord2)

    # 以下功能内容可以注释，进行单个功能调试

    # 提交问题,点赞点踩反馈
    commit_question(app, hwnd, input_box, zan_coord, cai_coord, commit_fankui_coord, send_coord1, send_coord2)

    # 上传文件提问
    upload_file(hwnd, app, input_box, docx_path_file_name, upload_file_coord, send_coord2)

    # 文档校对、 文档总结、 中英互译
    for name in fn_name:
        document_check(name, hwnd, app, upload_file_coord, docx_path_file_name, send_coord2)

    # 提示词帮助
    tips_help(app, hwnd, tips_help_coord, send_coord2)

    # 意见反馈
    suggestion(app)

    # excel助手
    excel_help(app, hwnd, input_box, upload_file_coord, excel_path_file_name, send_coord2)

    # 文档转换
    doc_convert(app, hwnd, upload_file_coord, excel_path_file_name, send_coord2)

    print("恭喜你！已经完成电投壹PC端deepseek全部功能测试。")

    # if res == 1:
    #     set_screen_resolution(old_resolution[0], old_resolution[1])


